#!/usr/bin/env python3
# -*- coding=utf-8 -*-
# 本脚由亁颐堂现任明教教主编写，用于乾颐盾Python课程！
# 教主QQ:605658506
# 亁颐堂官网www.qytang.com
# 教主技术进化论拓展你的技术新边疆
# https://ke.qq.com/course/271956?tuin=24199d8a

from devnet.models import Department, Navbar, Devicedb, MonitorInterval
from django.shortcuts import render
import json
from datetime import datetime, timedelta
from django.contrib.auth.decorators import permission_required


def get_mem_monitor_interval():
    try:
        mem_monitor_interval = MonitorInterval.objects.get(name='mem_interval').interval
    except MonitorInterval.DoesNotExist:
        m = MonitorInterval(name='mem_interval',
                            interval=1)
        m.save()
        mem_monitor_interval = MonitorInterval.objects.get(name='mem_interval').interval
    return mem_monitor_interval
    

@permission_required('devnet.view_devicemem')
def device_monitor_mem(request):
    html_title = Department.objects.get(name='admin').departtitle.title
    navbar_list = []
    for navbar in Navbar.objects.all().order_by('id'):
        navbar_list.append([navbar.name, navbar.url])
    active_navbar = '设备监控'
    sidebar_list = []
    for sidebar in Navbar.objects.get(name='设备监控').Sidebar.all().order_by('id'):
        sidebar_list.append([sidebar.name, sidebar.url])
    active_sidebar = '内存利用率'
    devices_list = []
    for device in Devicedb.objects.all().order_by('id'):
        devices_list.append({'id': device.id, 'name': device.name})

    current_obj = Devicedb.objects.all().order_by('id')[0]
    current = current_obj.name

    mem_usage_in_monitor_interval = current_obj.mem_usage.filter(record_datetime__gt=datetime.now() - timedelta(hours=get_mem_monitor_interval()))

    mem_usage = []
    mem_record_time = []

    for x in sorted(mem_usage_in_monitor_interval, key=lambda k: k.record_datetime):
        mem_usage.append(x.mem_usage)  # 把每一分钟采集到的CPU利用率写入mem_data清单
        # 把采集时间格式化然后写入mem_time清单
        mem_record_time.append(x.record_datetime.strftime('%H:%M'))
        # 返回'monitor_devices_cpu.html'页面,与设备清单, 当前设备, CPU利用率清单mem_data, CPU采集时间清单mem_time
        # 由于数据会被JavaScript使用, 所以需要使用JSON转换为字符串
    mem_data = json.dumps(mem_usage)
    mem_time = json.dumps(mem_record_time)
    
    return render(request, 'devnet_device_monitor_mem.html', locals())


@permission_required('devnet.view_devicemem')
def device_monitor_mem_device(request, device_id):
    html_title = Department.objects.get(name='admin').departtitle.title
    navbar_list = []
    for navbar in Navbar.objects.all().order_by('id'):
        navbar_list.append([navbar.name, navbar.url])
    active_navbar = '设备监控'
    sidebar_list = []
    for sidebar in Navbar.objects.get(name='设备监控').Sidebar.all().order_by('id'):
        sidebar_list.append([sidebar.name, sidebar.url])
    active_sidebar = '内存利用率'

    devices_list = []
    for device in Devicedb.objects.all().order_by('id'):
        devices_list.append({'id': device.id, 'name': device.name})

    current_obj = Devicedb.objects.get(id=device_id)
    current = current_obj.name

    mem_usage_in_monitor_interval = current_obj.mem_usage.filter(record_datetime__gt=datetime.now() - timedelta(hours=get_mem_monitor_interval()))

    mem_usage = []
    mem_record_time = []

    for x in sorted(mem_usage_in_monitor_interval, key=lambda k: k.record_datetime):
        mem_usage.append(x.mem_usage)  # 把每一分钟采集到的CPU利用率写入mem_data清单
        # 把采集时间格式化然后写入mem_time清单
        mem_record_time.append(x.record_datetime.strftime('%H:%M'))
        # 返回'monitor_devices_cpu.html'页面,与设备清单, 当前设备, CPU利用率清单mem_data, CPU采集时间清单mem_time
        # 由于数据会被JavaScript使用, 所以需要使用JSON转换为字符串
    mem_data = json.dumps(mem_usage)
    mem_time = json.dumps(mem_record_time)

    return render(request, 'devnet_device_monitor_mem.html', locals())
